Ext.namespace("Addama");
Ext.namespace("Addama.users");

Addama.users.UserAdmin = function() {

    // private variables
    var usersDS = new Ext.data.JsonStore({
        storeId: "users",
        url: "/addama-users/users",
        root: "users",
        fields: ["firstName", "lastName", "emailAddress"],
        sortInfo: {
            field: "lastName",
            direction: "ASC"
        }
    });

    var limsHomeStore = new Ext.data.SimpleStore({
        fields: ['key', 'value'],
        data : [
            ['Default', 'Default'],
            ['sample:yad', 'sample:yad'],
            ['sample:yo', 'sample:yo'],
            ['omics', 'omics']
        ]
    });

    // private functions    
    function onAddUser() {
        var win = new Ext.Window({
            title: "Add User",
            closable: false,
            modal: true,
            width: 400,
            autoHeight: true,
            items: [
                new Ext.form.FormPanel({
                    border: false,
                    items: getUserFieldSet(),
                    buttons: [
                        {
                            text: "Add",
                            handler: function() {
                                if (Ext.getCmp("emailAddressField").getValue() !== "" &&
                                    Ext.getCmp("firstNameField").getValue() !== "" &&
                                    Ext.getCmp("lastNameField").getValue() !== "") {
                                    addUserByForm();
                                    win.close();
                                }
                            }
                        },
                        {
                            text: "Cancel",
                            handler: function() {
                                win.close();
                            }
                        }
                    ]
                })
            ]
        });
        win.show();
    }

    function onEditUser() {
        var record = Ext.getCmp("usersGrid").getSelectionModel().getSelected();
        if (!record) return;
        var win = new Ext.Window({
            title: "Edit User",
            closable: false,
            modal: true,
            width: 400,
            autoHeight: true,
            items: [
                new Ext.form.FormPanel({
                    border: false,
                    items: getUserFieldSet(record),
                    buttons: [
                        {
                            text: "Save",
                            handler: function() {
                                saveUserByForm();
                                win.close();
                            }
                        },
                        {
                            text: "Cancel",
                            handler: function() {
                                win.close();
                            }
                        }
                    ]
                })
            ]
        });
        win.show();
    }

    function getHomeCombo(pref) {
        return new Ext.form.ComboBox({
            store: limsHomeStore,
            name: 'limsHome',
            id: 'limsHomeId',
            fieldLabel: 'LIMS Home',
            displayField:'value',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            value:pref ? pref : 'Default',
            forceSelection:true,
            width:220,
            selectOnFocus:true
        });
    }

    function onEditHome() {
        var record = Ext.getCmp("usersGrid").getSelectionModel().getSelected();
        if (!record) return;
        var userurl = "/addama-rest/primary-repo/path/users/" + record.data.emailAddress;
        Ext.Ajax.request({
            url: userurl + "/annotations",
            method: "get",
            success: function (response) {
                var jsonObj = Ext.util.JSON.decode(response.responseText);
                var limshome = jsonObj.limshome;
                var win = new Ext.Window({
                    title: "Edit Home",
                    closable: false,
                    modal: true,
                    width: 400,
                    autoHeight: true,
                    items: [
                        new Ext.form.FormPanel({
                            border: false,
                            items: getHomeCombo(limshome),
                            buttons: [
                                {
                                    text: "Save",
                                    handler: function() {
                                        var newPref = Ext.getCmp("limsHomeId").getValue();
                                        if (newPref.toLowerCase() != "default") {
                                            var prefJson = new Object();
                                            prefJson['limshome'] = newPref;
                                            postDudleyAnnotations(userurl + '/annotations', prefJson, function() {
                                                eventManager.fireStatusMessageEvent({ text: "LIMS Home Preference Updated", level: "info" });
                                            });
                                        }
                                        win.close();
                                    }
                                },
                                {
                                    text: "Cancel",
                                    handler: function() {
                                        win.close();
                                    }
                                }
                            ]
                        })
                    ]
                });
                win.show();
            }
        });
    }

    function onDeleteUser() {
        var username = getSelectedUsername();
        if (!username) return;
        Addama.users.UserAdmin.deleteUser(username, function() {
            updateUsers();
        });
    }

    function onResetPassword() {
        var username = getSelectedUsername();
        if (!username) return;

        Addama.users.UserAdmin.resetPassword(username, function() {
            updateUsers();
        });
    }

    function getSelectedUsername() {
        var grid = Ext.getCmp("usersGrid");
        if (grid.getSelectionModel().getSelected()) {
            return grid.getSelectionModel().getSelected().data.emailAddress;
        }
        else return undefined;
    }

    function onUserSelect() {
        Ext.getCmp("editUserButton").enable();
        Ext.getCmp("editHomeButton").enable();
        Ext.getCmp("deleteUserButton").enable();
        Ext.getCmp("resetPasswordButton").enable();
    }

    function updateUsers() {
        Ext.StoreMgr.lookup("users").reload();
    }

    function getUserFieldSet(record) {

        return new Ext.form.FieldSet({
            autoHeight: true,
            border: false,
            items: [
                new Ext.form.TextField({
                    id: "emailAddressField",
                    fieldLabel: "Email",
                    name: "emailAddress",
                    readOnly: (record ? true : false),
                    style: (record ? "background:transparent;border:none;" : undefined),
                    value: (record ? record.data.emailAddress : undefined),
                    allowBlank: false,
                    width: 150,
                    grow: true,
                    growMin: 150
                }),
                new Ext.form.TextField({
                    id: "firstNameField",
                    fieldLabel: "First name",
                    name: "firstName",
                    width: 150,
                    value: (record ? record.data.firstName : undefined),
                    allowBlank: false
                }),
                new Ext.form.TextField({
                    id: "lastNameField",
                    fieldLabel: "Last Name",
                    name: "lastName",
                    width: 150,
                    value: (record ? record.data.lastName : undefined),
                    allowBlank: false
                })
            ]
        });
    }

    /*
     Ext.Ajax.request({
     url: "/addama-rest/primary-repo/path/users/" + record.data.emailAddress + "/annotations",
     method: "get",
     success: function (response){
     var jsonObj = Ext.util.JSON.decode(response.responseText);
     var limshome = jsonObj.limshome;

     */
    function addUserByForm() {
        Addama.users.UserAdmin.addUser({
            emailAddress: Ext.getCmp("emailAddressField").getValue(),
            firstName: Ext.getCmp("firstNameField").getValue(),
            lastName: Ext.getCmp("lastNameField").getValue(),
            callback: function() {
                updateUsers();
            }
        });
    }

    function saveUserByForm() {
        Addama.users.UserAdmin.saveUser({
            emailAddress: Ext.getCmp("emailAddressField").getValue(),
            firstName: Ext.getCmp("firstNameField").getValue(),
            lastName: Ext.getCmp("lastNameField").getValue(),
            callback: function() {
                updateUsers();
            }
        });
    }

    // public
    return {
        // public properties

        // public methods
        deleteUser: function(username, callOnSuccess) {
            Ext.Ajax.request({
                url: "/addama-users/users/" + username + "/delete",
                method: "post",
                success: callOnSuccess,
                failure: function() {
                    Ext.MessageBox.show({
                        title: "Error",
                        msg: "An error occurred while deleting user '" + username + "'.",
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    });
                }
            });
        },

        resetPassword: function(username, callOnSuccess) {
            Ext.Ajax.request({
                url: "/addama-users/users/" + username + "/password_reset",
                method: "post",
                success: function() {
                    callOnSuccess();
                    Ext.MessageBox.show({
                        title: "Info",
                        msg: "Resetting user password and sending email to user '" + username + "'.",
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.INFO
                    });
                },
                failure: function() {
                    Ext.MessageBox.show({
                        title: "Error",
                        msg: "An error occurred while resetting password for user '" + username + "'.",
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    });
                }
            });
        },

        addUser: function(o) {
            var json = {
                firstName: o.firstName,
                lastName: o.lastName
            };
            Ext.Ajax.request({
                url: "/addama-users/users/" + o.emailAddress + "/create",
                method: "post",
                params: {
                    JSON: Ext.encode(json)
                },
                success: o.callback,
                failure: function() {
                    Ext.MessageBox.show({
                        title: "Error",
                        msg: "An error occurred while adding user '" + o.emailAddress + "'.",
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    });
                }
            });
        },

        saveUser: function(o) {
            var json = {
                emailAddress: o.emailAddress,
                firstName: o.firstName,
                lastName: o.lastName
            };
            Ext.Ajax.request({
                url: "/addama-users/users/" + o.emailAddress,
                method: "post",
                params: {
                    JSON: Ext.encode(json)
                },
                success: o.callback,
                failure: function() {
                    Ext.MessageBox.show({
                        title: "Error",
                        msg: "An error occurred while saving user '" + o.emailAddress + "'.",
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    });
                }
            });
        },

        loadUsers: function() {
            new Ext.Panel({
                width: 700,
                height: 500,
                border: true,
                renderTo: "content-users",
                items: [
                    new Ext.grid.GridPanel({
                        id: "usersGrid",
                        title: "Users",
                        store: usersDS,
                        columns: [
                            {
                                id: "firstName",
                                header: "First name",
                                sortable: true,
                                dataIndex: "firstName"
                            },
                            {
                                id: "lastName",
                                header: "Last name",
                                sortable: true,
                                dataIndex: "lastName"
                            },
                            {
                                id: "emailAddress",
                                header: "Email",
                                sortable: true,
                                dataIndex: "emailAddress"
                            }
                        ],
                        viewConfig: {
                            forceFit: true
                        },
                        sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
                        stripeRows: true,
                        height: 500,
                        autoWidth: true,
                        border: false,
                        tbar: [
                            new Ext.Button({
                                id: "addUserButton",
                                text: "Add",
                                handler: onAddUser
                            }),
                            new Ext.Button({
                                id: "editUserButton",
                                text: "Edit Details",
                                handler: onEditUser,
                                disabled: true
                            }),
                            new Ext.Button({
                                id: "editHomeButton",
                                text: "Set LIMSHome",
                                handler: onEditHome,
                                disabled: true
                            }),

                            new Ext.Button({
                                id: "deleteUserButton",
                                text: "Delete",
                                handler: onDeleteUser,
                                disabled: true
                            }),
                            new Ext.Button({
                                id: "resetPasswordButton",
                                text: "Reset Password",
                                handler: onResetPassword,
                                disabled: true
                            })
                        ],
                        listeners: {
                            rowclick: onUserSelect
                            //dblclick: onEditUser
                        }
                    })
                ]
            });

            Ext.StoreMgr.lookup("users").load();
        },

        init: function() {
            Ext.Ajax.request({
                url: "/addama-rest/primary-repo/path/users/create",
                method: "post",
                success: Addama.users.UserAdmin.loadUsers,
                failure: Addama.users.UserAdmin.loadUsers
            });
        }
    };
}();
